package com.five.novel.service.Impl;

import com.five.basic.result.PageList;
import com.five.basic.service.impl.BaseServiceImpl;
import com.five.novel.mapper.NovelCategoryMapper;
import com.five.novel.service.INovelCategoryService;
import com.five.pojo.Novel;
import com.five.pojo.NovelCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class NovelCategoryServiceImpl extends BaseServiceImpl<NovelCategory> implements INovelCategoryService {

    @Autowired
    private NovelCategoryMapper novelCategoryMapper;

    /*
    * 小说类型分类树
    * */
    @Transactional
    @Override
    public List<NovelCategory> novelCategoryTree(Long type) {
        // 1. 查询所有分类
        List<NovelCategory> list = novelCategoryMapper.queryByType(type);
//        List<NovelCategory> list = novelCategoryMapper.queryAll();

        // 2. 转成map
        HashMap<Long, NovelCategory> map = new HashMap<>();
        for (NovelCategory novelCategory : list) {
            map.put(novelCategory.getId(), novelCategory);
        }

        //准备树形结构
        List<NovelCategory> tree = new ArrayList<>();
        for (NovelCategory novelCategory : list) {

            // 判断是否是父级（parentId为null或0表示根节点）
            if (novelCategory.getParentId() == null || novelCategory.getParentId() == 0) {
                tree.add(novelCategory);
            } else {

                // 获取父级
                NovelCategory parent = map.get(novelCategory.getParentId());

                // 添加到父级
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(novelCategory);
                }
            }
        }
        return tree;
    }



    /*
    *根据性别分类类型分页查询
    * */

    @Override
    public PageList<NovelCategory> queryByType(Long type) {
        if(type != null){
            //根据type查询并分页
            NovelCategory queryCondition = new NovelCategory();
            queryCondition.setType(type.intValue());
            Integer total = novelCategoryMapper.queryCount(queryCondition);
            if (total == null || total == 0) {
                return new PageList<>();
            }
            List<NovelCategory> data = novelCategoryMapper.queryPage(queryCondition);
            return new PageList<>(total,data);
        }
        //返回所有类型并作分页
        Integer total = novelCategoryMapper.queryCount(new NovelCategory());
        if (total == null || total == 0) {
            return new PageList<>();
        }
        NovelCategory queryCondition = new NovelCategory();
        List<NovelCategory> data = novelCategoryMapper.queryPage(queryCondition);
        return new PageList<>(total,data);
    }
}